﻿using System;
using System.Collections.Generic;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Criterion;
using ScoutersLog.DataAccess.Mappings;

namespace ScoutersLog.DataAccess.Persistence
{
    public class SharedSession
    {
        private static readonly ISessionFactory SessionFactory = CreateSessionFactory();
        private static ISession _session;
        internal static ISession Session
        {
            get
            {
                if (_session == null)
                    _session = SessionFactory.OpenSession();
                return _session;
            }
        }
        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(MsSqlCeConfiguration.Standard
                    .ConnectionString(@"Data Source=D:\Projects\ScoutersLog\Model.UnitTests\bin\Debug\ScoutersLog.sdf"))
                .Mappings(m => m.FluentMappings
                    .AddFromAssemblyOf<CouncilMap>()
                    .Conventions.AddFromAssemblyOf<DbCaseTableNameConvention>())
                .BuildSessionFactory();
        }
        public static void SaveOrUpdate(object obj)
        {
            if (obj == null) throw new ArgumentNullException("obj");
            using (var transaction = Session.BeginTransaction())
            {
                Session.SaveOrUpdate(obj);
                transaction.Commit();
            }
        }
        public static object Get(Type type, object id)
        {
            using (Session.BeginTransaction())
            {
                return Session.Get(type, id);
            }
        }
        public static IList<T> LoadList<T>(string orderBy)
        {
            if (Session.IsDirty())
                Session.Flush();
            using (Session.BeginTransaction())
            {
                return Session.CreateCriteria(typeof (T))
                    .AddOrder(Order.Asc(orderBy))
                    .List<T>();
            }
        }
        public static void Delete(object obj)
        {
            if (obj == null) throw new ArgumentNullException("obj");
            using (var transaction = Session.BeginTransaction())
            {
                Session.Delete(obj);
                transaction.Commit();
            }
        }
    }
}